//
//  DiscoverTableViewCell.m
//  Wifi
//
//  Created by srulos on 2017/6/12.
//  Copyright © 2017年 srulos. All rights reserved.
//

#import "DiscoverTableViewCell.h"
#import "FLAnimatedImage.h"
#import "WifiHeader.h"

@implementation DiscoverTableViewCell
@synthesize m_thumbImageUrl;
@synthesize m_downloadUrl;
@synthesize delegate;

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

- (void)setup:(NSMutableDictionary *)dic
{
    _m_imageView.image = nil;
    _m_imageView.animatedImage = nil;
    
    _m_label_title.text = [dic objectForKey:@"text"];
    
    if ([dic objectForKey:@"image"] != nil) {//image
        self.m_btn_playVideo.hidden = YES;
        self.m_btn_full_screen_image.hidden = NO;
        self.m_label_background_mask.hidden = NO;
        
        self.m_imageView_cell_tag.image = nil;//[UIImage imageNamed:@"longImage"];
        
        NSMutableDictionary * dataDic = [dic objectForKey:@"image"];
        m_downloadUrl = [[dataDic objectForKey:@"download_url"] objectAtIndex:0];
        m_thumbImageUrl = [[dataDic objectForKey:@"download_url"] objectAtIndex:0];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UIImage * image = [UIImage imageWithData:[self getDataFromCache:m_downloadUrl]];

            CGSize imageSize = image.size;
            
            //偏移量
            CGFloat offsetScale = imageSize.width / _m_imageView.frame.size.width;
            imageSize.height = imageSize.height / offsetScale;
            
            image = [self compressOriginalImage:image toSize:CGSizeMake(_m_imageView.frame.size.width, imageSize.height)];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                _m_imageView.image = image;
                _m_imageView.contentMode = UIViewContentModeTop;
                _m_imageView.clipsToBounds = YES;//超出部分剪掉
            });
        });
    }
    else if([dic objectForKey:@"gif"] != nil){//gif
        self.m_btn_playVideo.hidden = YES;
        self.m_btn_full_screen_image.hidden = NO;
        self.m_label_background_mask.hidden = NO;
        
        self.m_imageView_cell_tag.image = [UIImage imageNamed:@"gifImage"];
        
        NSMutableDictionary * dataDic = [dic objectForKey:@"gif"];
        m_downloadUrl = [[dataDic objectForKey:@"images"] objectAtIndex:0];
        m_thumbImageUrl = [[dataDic objectForKey:@"gif_thumbnail"] objectAtIndex:0];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            FLAnimatedImage * animationImage = [[FLAnimatedImage alloc]initWithAnimatedGIFData:[self getDataFromCache:m_downloadUrl]];

            dispatch_async(dispatch_get_main_queue(), ^{
                _m_imageView.animatedImage = animationImage;
                _m_imageView.contentMode = UIViewContentModeTop;
                _m_imageView.clipsToBounds = YES;//超出部分剪掉
            });
        });
    }
    else if([dic objectForKey:@"video"] != nil){//video
        self.m_btn_playVideo.hidden = NO;
        self.m_btn_full_screen_image.hidden = YES;
        self.m_label_background_mask.hidden = YES;
        
        self.m_imageView_cell_tag.image = nil;//[UIImage imageNamed:@"video"];
        
        NSMutableDictionary * dataDic = [dic objectForKey:@"video"];
        m_downloadUrl = [[dataDic objectForKey:@"download"] objectAtIndex:0];
        m_thumbImageUrl = [[dataDic objectForKey:@"thumbnail"] objectAtIndex:0];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UIImage * image = [UIImage imageWithData:[self getDataFromCache:m_thumbImageUrl]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                _m_imageView.image = image;
            });
        });
    }
}

-(UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
    UIImage * resultImage = image;
    UIGraphicsBeginImageContext(size);
    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIGraphicsEndImageContext();
    return image;
}

- (NSData*)getDataFromCache:(NSString*)url{
    NSData * data = [[WQMemoryCacheManager stander]getData:url];
    if (data == nil) {
        data = [[WQCacheManager standard]getFile:url];
        if (data == nil) {
            data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            [[WQCacheManager standard]writeFile:data fileName:url];
        }
        if (data != nil) {
            [[WQMemoryCacheManager stander]addData:data key:url];
        }
    }
    return data;
}

- (IBAction)onPlayVideo:(id)sender {
    UIViewController * rootVc = [UIApplication sharedApplication].keyWindow.rootViewController;

    if (IS_PASS && IS_CHINESE && IS_IPAD && ![MPWeChat stander].m_isLogin) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"login" bundle:nil];
        UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [rootVc presentViewController:vc animated:YES completion:nil];
        return;
    }
    if ([[MyAdTools shareInstance] showInterstitialWithVC:rootVc]) {
        return;
    }

    UIWebView * webView = [[UIWebView alloc]initWithFrame:_m_imageView.frame];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:m_downloadUrl]]];
    webView.scrollView.scrollEnabled = NO;
    [self.contentView addSubview:webView];
}

- (IBAction)onFullScreenImage:(id)sender {
    UIViewController * rootVc = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    if (IS_PASS && IS_CHINESE && IS_IPAD && ![MPWeChat stander].m_isLogin) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"login" bundle:nil];
        UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [rootVc presentViewController:vc animated:YES completion:nil];
        return;
    }
    if ([[MyAdTools shareInstance] showInterstitialWithVC:rootVc]) {
        return;
    }
    
    if (delegate != nil && [delegate respondsToSelector:@selector(onShowImage:isGif:)]) {
        BOOL isGif = NO;
        
        if ([m_downloadUrl.lastPathComponent rangeOfString:@"gif"].location != NSNotFound || [m_downloadUrl.lastPathComponent rangeOfString:@"GIF"].location != NSNotFound) {
            isGif = YES;
        }
        
        [delegate onShowImage:[self getDataFromCache:m_downloadUrl] isGif:isGif];
    }
}

- (IBAction)onSystemShare:(id)sender {
    UIViewController * rootVc = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    if (IS_PASS && IS_CHINESE && IS_IPAD && ![MPWeChat stander].m_isLogin) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"login" bundle:nil];
        UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [rootVc presentViewController:vc animated:YES completion:nil];
        return;
    }
    if ([[MyAdTools shareInstance] showInterstitialWithVC:rootVc]) {
        return;
    }
    
    NSString *textToShare = _m_label_title.text;
    UIImage * imageToShare = _m_imageView.image;
    NSURL *urlToShare = [NSURL URLWithString:m_downloadUrl];
    
    NSMutableArray *activityItems = [[NSMutableArray alloc]init];
    
    if (textToShare != nil) {
        [activityItems addObject:textToShare];
    }
    
    if (imageToShare != nil) {
        [activityItems addObject:imageToShare];
    }
    
    if (urlToShare != nil) {
        [activityItems addObject:urlToShare];
    }
    
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems
                                                                            applicationActivities:nil];
    
    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll,UIActivityTypeAddToReadingList];
    
    UIActivityViewControllerCompletionWithItemsHandler myBlock = ^(UIActivityType activityType, BOOL completed, NSArray * returnedItems, NSError * activityError){
        
    };
    
    activityVC.completionWithItemsHandler = myBlock;

    [rootVc presentViewController:activityVC animated:TRUE completion:nil];
}

@end
